package com.lindroy.androidplayer

import android.content.Context
import android.content.Intent
import android.os.SystemClock
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.fragment.app.viewModels
import com.lindroy.androidplayer.base.BaseActivity
import com.lindroy.androidplayer.base.appViewModel
import com.lindroy.androidplayer.extensions.*
import com.lindroy.androidplayer.logic.model.LoginResp
import com.lindroy.androidplayer.logic.network2.NetworkService
import com.lindroy.androidplayer.logic.network2.apiService
import com.lindroy.androidplayer.ui.coin.CoinHistoryActivity
import com.lindroy.androidplayer.ui.coin.CoinRankActivity
import com.lindroy.androidplayer.ui.collection.CollectionActivity
import com.lindroy.androidplayer.ui.home.fragment.HomeFragment
import com.lindroy.androidplayer.ui.home.fragment.KnowledgeFragment
import com.lindroy.androidplayer.ui.home.fragment.OfficialAccountFragment
import com.lindroy.androidplayer.ui.home.fragment.ProjectFragment
import com.lindroy.androidplayer.ui.login.LoginActivity
import com.lindroy.androidplayer.ui.login.LoginViewModel
import com.lindroy.androidplayer.ui.scan.ScanActivity
import com.lindroy.androidplayer.ui.search.SearchActivity
import com.lindroy.androidplayer.viewmodel.CoinViewModel
import com.lindroy.androidplayer.viewmodel.UpdateViewModel
import com.lindroy.lib_utils.extensions.*
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.toolbar.*

/**
 * @author Lin
 * @date 2021/4/9
 * @function 首页
 * @Description
 */
class MainActivity(override val layoutId: Int = R.layout.activity_main) : BaseActivity() {
    private var homeFragment: HomeFragment? = null
    private var officialFragment: OfficialAccountFragment? = null
    private var projectFragment: ProjectFragment? = null
    private var knowledgeFragment: KnowledgeFragment? = null
    private val navHeaderView by lazy { navView.getHeaderView(0) }
    private val tvUserName by lazy { navHeaderView.findViewById<TextView>(R.id.tvUserName) }
    private val tvCoinInfo by lazy { navHeaderView.findViewById<TextView>(R.id.tvCoinInfo) }
    private val ivRank by lazy { navHeaderView.findViewById<ImageView>(R.id.ivRank) }
    private val loginViewModel: LoginViewModel by viewModels()
    private val coinViewModel: CoinViewModel by viewModels()
    private val updateViewModel: UpdateViewModel by viewModels()

    companion object {
        fun start(context: Context) {
            context.launchActivity<MainActivity>()
        }
    }

    private val mHits = LongArray(2)

    override fun initView() {
        initToolBar(R.string.app_name, true)
        showHomeFragment()
        //关联Toolbar和侧边栏的开关，可以选左上角的菜单图标
        val toggle = ActionBarDrawerToggle(
            this,
            drawerLayout,
            toolBar,
            R.string.navigation_drawer_open,
            R.string.navigation_drawer_close
        )
        drawerLayout.addDrawerListener(toggle)
        toggle.syncState()
        appViewModel.loginInfo.value?.let {
            tvUserName.text = it.username.isNotEmpty().yes { it.username }
                .no { getResString(R.string.hint_login) }
        }
        addLoadingObserve(loginViewModel)
        showLogoutItem()
    }

    override fun initData() {
        coinViewModel.reqCoinInfo()
        updateViewModel.reqUpdateInfo()
    }

    override fun initListener() {
        appViewModel.loginInfo.observeInActivity(this) {
            tvUserName.text = it.isLogin.yes {
                tvCoinInfo.setVisible()
                it.username
            }.no {
                tvCoinInfo.setGone()
                getResString(R.string.hint_login)
            }
            showLogoutItem()

        }
        loginViewModel.logoutResult.observe(this) { resultState ->
            parseState(resultState) {
                shortToast(getString(R.string.logout_success))
                clearSp()
                NetworkService.instance.clearCookie()
                appViewModel.loginInfo.value = LoginResp()
            }
        }
        coinViewModel.coinInfoState.observe(this) { resultState ->
            parseState(resultState) {
                globalLoginInfo.coinCount = it.coinCount
                //计算等级，每一百分一个等级
                val grade = (it.coinCount / 100) + 1
                tvCoinInfo.text = getString(R.string.nav_coin_info, grade, it.rank)
            }
        }
        updateViewModel.updateLiveData.observe(this){resultState->
            parseState(resultState){
                Logger.d(it)
            }
        }
        //增加挤压效果之后，首页会向上滑动一点距离，故先不加动画.
        /* drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener{
             override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
                 //让首页CoordinatorLayout跟着DrawerLayout移动
                 coordinatorLayout.layout(navView.right,0,navView.right+screenWidth, screenHeight)
             }

             override fun onDrawerOpened(drawerView: View) {
             }

             override fun onDrawerClosed(drawerView: View) {
             }

             override fun onDrawerStateChanged(newState: Int) {
             }

         })*/
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        homeFragment?.isVisibleToUser?.yes {
            menuInflater.inflate(R.menu.home_search_menu, menu)
        }
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.action_search -> {
                launchActivity<SearchActivity>()
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun initClick() {
        fun login() {
            globalLoginInfo.isLogin.not().yes {
                launchActivity<LoginActivity>()
            }
        }
        tvUserName.setOnClickListener {
            login()
        }
        navView.getHeaderView(0).findViewById<ImageView>(R.id.ivAvatar).setOnClickListener {
            login()
        }
        navView.setNavigationItemSelectedListener {
            drawerLayout.closeDrawers()
            when (it.itemId) {
                R.id.navScore -> launchActivity<CoinHistoryActivity>()
                R.id.navCollection -> {
                    globalLoginInfo.isLogin.yes {
                        launchActivity<CollectionActivity>()
                    }.no {
                        shortToast(R.string.hint_login)
                        launchActivity<LoginActivity>()
                    }
                }
                R.id.navScan-> launchActivity<ScanActivity>()
                R.id.navLogout -> loginViewModel.logout()
            }
            true
        }
        bottomNav.setOnNavigationItemSelectedListener { it ->
            when (it.itemId) {
                R.id.nav_home -> showHomeFragment()
                R.id.nav_wechat -> showOfficialAccountFragment()
                R.id.nav_knowledge -> showKnowledgeFragment()
                R.id.nav_project -> showProjectFragment()
            }
            true
        }
        ivRank.setOnClickListener {
            launchActivity<CoinRankActivity>()
        }
    }

    private fun showHomeFragment() {
        val ft = supportFragmentManager.beginTransaction()
        if (homeFragment == null) {
            homeFragment = HomeFragment.newInstance()
            ft.add(R.id.flContainer, homeFragment!!)
        }
        hideAllFragment(ft)
        ft.show(homeFragment!!)
        ft.commit()
        setToolBarTitle(R.string.home)
    }

    private fun showOfficialAccountFragment() {
        val ft = supportFragmentManager.beginTransaction()
        if (officialFragment == null) {
            officialFragment = OfficialAccountFragment.newInstance()
            ft.add(R.id.flContainer, officialFragment!!)
        }
        hideAllFragment(ft)
        ft.show(officialFragment!!).commit()
        setToolBarTitle(R.string.official_account)
    }

    private fun showProjectFragment() {
        val ft = supportFragmentManager.beginTransaction()
        if (projectFragment == null) {
            projectFragment = ProjectFragment.newInstance()
            ft.add(R.id.flContainer, projectFragment!!)
        }
        hideAllFragment(ft)
        ft.show(projectFragment!!).commit()
        setToolBarTitle(R.string.project)
    }

    private fun showKnowledgeFragment() {
        val ft = supportFragmentManager.beginTransaction()
        if (knowledgeFragment == null) {
            knowledgeFragment = KnowledgeFragment.newInstance()
            ft.add(R.id.flContainer, knowledgeFragment!!)
        }
        hideAllFragment(ft)
        ft.show(knowledgeFragment!!).commit()
        setToolBarTitle(R.string.knowledge_system)
    }

    private fun hideFragment(ft: FragmentTransaction, fragment: Fragment?) {
        if (fragment != null) {
            ft.hide(fragment)
        }
    }

    private fun hideAllFragment(ft: FragmentTransaction) {
        hideFragment(ft, homeFragment)
        hideFragment(ft, officialFragment)
        hideFragment(ft, projectFragment)
        hideFragment(ft, knowledgeFragment)
    }

    override fun onBackPressed() {
        System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
        mHits[mHits.size - 1] = SystemClock.uptimeMillis()//开机后计算的时间
        if (mHits[0] < (SystemClock.uptimeMillis() - 1500)) { //1500为最后一次点击和第一次点击的间隔时间
            shortToast(getString(R.string.exit_app))
        } else {
            super.onBackPressed()
        }
    }

    private fun showLogoutItem() {
        navView.menu.findItem(R.id.navLogout).isVisible = globalLoginInfo.isLogin
    }

    /**
     * 避免Fragment重叠
     */
    override fun onAttachFragment(fragment: Fragment) {
        super.onAttachFragment(fragment)
        when {
            homeFragment == null && fragment is HomeFragment -> {
                homeFragment = fragment
            }
            officialFragment == null && fragment is OfficialAccountFragment -> {
                officialFragment = fragment
            }
            projectFragment == null && fragment is ProjectFragment -> {
                projectFragment = fragment
            }
            knowledgeFragment ==null && fragment is KnowledgeFragment->{
                knowledgeFragment = fragment
            }
        }
    }

}